﻿using System;
using System.Web.UI.WebControls;
using System.Xml;

namespace KPI.Controls
{
	public partial class ThemeSelect : System.Web.UI.UserControl
	{
		protected void Page_Load(object sender, EventArgs e)
		{
			if(!IsPostBack)
			{
				if(ddlTheme.Items == null || ddlTheme.Items.Count <= 0)
				{
					BindThemes();
				}
			}
		}

		protected void ddlTheme_SelectedIndexChanged(object sender, EventArgs e)
		{
			KPISiteContext.Current.AppTheme = ddlTheme.SelectedValue;
			Server.Transfer(Request.FilePath);
		}

		protected void Page_PreRender(object sender, EventArgs e)
		{
			var currentTheme = KPISiteContext.Current.AppTheme;

			if(ddlTheme.Items != null && ddlTheme.Items.Count > 1)
			{
				foreach(ListItem item in ddlTheme.Items)
				{
					item.Selected = item.Value.Equals(currentTheme);
				}
			}
		}

		private void BindThemes()
		{
			var xmlDoc = GetThemeDoc();

			try
			{
				if(xmlDoc.DocumentElement != null && xmlDoc.DocumentElement.HasChildNodes)
				{
					foreach(XmlNode node in xmlDoc.DocumentElement.ChildNodes)
					{
						var v = node.Attributes["value"].Value;
						var t = node.Attributes["text"].Value;

						var listItem = new ListItem(t, v);

						ddlTheme.Items.Add(listItem);
					}
				}
			}
			catch
			{
				throw;
			}
		}

		private XmlDocument GetThemeDoc()
		{
			XmlDocument result = null;

			try
			{
				if(Cache["sitethemedoc"] == null)
				{
					var doc = new XmlDocument();
					doc.Load(Server.MapPath("/") + "Themes.xml");

					Cache.Add("sitethemedoc", doc, new System.Web.Caching.CacheDependency(Server.MapPath("/") + "Themes.xml"), System.Web.Caching.Cache.NoAbsoluteExpiration, new TimeSpan(12, 0, 0), System.Web.Caching.CacheItemPriority.Default, null);
				}

				result = Cache["sitethemedoc"] as XmlDocument;
			}
			catch
			{
				throw;
			}

			return result;
		}
	}
}